package cn.ac.iie.di.ban.data.exchange.runner.master.helper.HttpHelper;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

/**
 * Created by Black-Laptop on 8/17/2017.
 */
public class HttpHelper {

    public static Logger LOG = Logger.getLogger(HttpHelper.class);

    public static String httpPost(String url, String body) throws Exception {

        URL restServiceURL;
        HttpURLConnection httpConnection = null;
        try {
            restServiceURL = new URL(url);
            httpConnection = (HttpURLConnection) restServiceURL.openConnection();
            httpConnection.setRequestMethod("POST");
            httpConnection.setRequestProperty("Accept", "application/json");
            httpConnection.setRequestProperty("Content-Type", "application/json");
            httpConnection.setDoOutput(true);
            httpConnection.connect();
            OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream(), "UTF-8");
            out.append(body);
//            LOG.debug(out.toString());
            out.flush();
            out.close();
            LOG.debug(body);
//            LOG.debug(JSONArray.parseArray(body));
            int status = httpConnection.getResponseCode();
            if (status != 200 && status != 204) {
                BufferedReader responseBuffer = new BufferedReader(
                        new InputStreamReader((httpConnection.getErrorStream())));
                StringBuffer errorMess = new StringBuffer();
                String output;
                while ((output = responseBuffer.readLine()) != null) {
                    errorMess.append(output);
                }
                throw new RuntimeException("HTTP POST Request Failed with Error code : "
                        + httpConnection.getResponseCode() + errorMess.toString());
            }
            BufferedReader responseBuffer = new BufferedReader(
                    new InputStreamReader((httpConnection.getInputStream())));
            StringBuilder resultMess = new StringBuilder();
            String output;
            while ((output = responseBuffer.readLine()) != null) {
                resultMess.append(output);
            }
            return resultMess.toString();
        } catch (Exception e) {
            LOG.error(ExceptionUtils.getFullStackTrace(e));
            throw new Exception(e.getMessage());
        } finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
        }
    }

    public static String httpPost(String url, List<NameValuePair> params) throws Exception {
        try {
            CloseableHttpResponse response = null;
            for (int i = 0; i <= 5; i++) {
                CloseableHttpClient client = HttpClients.createDefault();
                HttpPost post = new HttpPost(url);
                post.setEntity(new UrlEncodedFormEntity(params));

                response = client.execute(post);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();//是否发送成功，200即为成功
                LOG.debug("result back status:" + statusCode);
                if (statusCode == 200) {

                    break;
                }
            }

            InputStream is = response.getEntity().getContent();//得到返回流，读取并操作。
            StringBuilder result = new StringBuilder();
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            LOG.debug("result back :" + result.toString());
            return result.toString();
        } catch (NoSuchFieldError e) {
            LOG.error(ExceptionUtils.getFullStackTrace(e));
            throw new Exception(ExceptionUtils.getFullStackTrace(e));
        } catch (Exception | Error e) {
            LOG.error(ExceptionUtils.getFullStackTrace(e));
            throw new Exception(ExceptionUtils.getFullStackTrace(e));
        }
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static String httpGet(String url) {
        //get请求返回结果
//        String strResult = null;
//        try {
//            DefaultHttpClient client = new DefaultHttpClient();
//            //发送get请求
//            HttpGet request = new HttpGet(url);
//            HttpResponse response = null;
//            try {
//                response = client.execute(request);
//            } catch (IOException e) {
//                LOG.error(ExceptionUtils.getFullStackTrace(e));
//            }
//
//            /**请求发送成功，并得到响应**/
//            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//                /**读取服务器返回过来的json字符串数据**/
//                strResult = EntityUtils.toString(response.getEntity());
//                /**把json字符串转换成json对象**/
//                url = URLDecoder.decode(url, "UTF-8");
//            } else {
//                LOG.error("get请求提交失败:" + url);
//            }
//        } catch (IOException e) {
//            LOG.error("get请求提交失败:" + url, e);
//        }
//        return strResult;
        return null;
    }
}
